package com.tticar.invmanager.common.generator;

import com.baomidou.mybatisplus.generator.config.po.TableField;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yandou on 2018/6/16.
 */
public class MyFreemarkerTemplateEngine extends FreemarkerTemplateEngine {

    @Override
    public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
        if (templatePath.startsWith("null")) {
            return;
        }

        if (outputFile.endsWith(".ftl") && !outputFile.endsWith("_edit.ftl")) {
            String entity = objectMap.get("entity").toString();
            entity = entity.substring(0, 1).toLowerCase() + entity.substring(1);
            entity = "/" + entity + ".ftl";

            String op = outputFile.replace(entity, "").replace(".ftl", "");
//            File file = new File("/Users/yandou/java/workspace/invmanager/src/main/resources/templates/sysResource");
            File file = new File(op);
            if (!file.exists()) {
                file.mkdir();
            }
        }
        objectMap.put("cfg", getConfigBuilder().getInjectionConfig().getMap());
        objectMap.put("csslib", "<#include \"./../common/lib/csslib.ftl\">");
        objectMap.put("jslib", "<#include \"./../common/lib/jslib.ftl\">");

        List<Map> comboList = new ArrayList();
        TableInfo tableInfo = (TableInfo) objectMap.get("table");
        for (TableField tableField : tableInfo.getFields()) {
            String type = tableField.getPropertyType();
            String name = tableField.getPropertyName();
            if ("Long".equals(type) && name.endsWith("Id")) {
                Map map = new HashMap();
                map.put("name", name);
                map.put("pre", name.substring(0, name.length() - 2));
                comboList.add(map);
            }
        }

        objectMap.put("comboList", comboList);

        super.writer(objectMap, templatePath, outputFile);
    }
}
